<template>
  <div class="queue-query-page">
    <!-- 顶部导航栏 -->
    <van-nav-bar
      title="候诊查询"
      left-arrow
      @click-left="onBack"
    />
    
    <!-- 患者信息卡片（仅当有选中患者时显示） -->
    <div class="patient-info-card" v-if="queueInfo">
      <div class="patient-header">
        <div class="patient-name">{{ queueInfo.patientName }} 
          <span class="relation">{{ currentPatientRelation }}</span>
        </div>
        <div class="change-patient" @click="showPatientPicker = true">
          切换就诊人
          <svg width="18" height="18" viewBox="0 0 20 20"><circle cx="10" cy="10" r="9" stroke="#338aff" stroke-width="2" fill="#fff"/><path d="M7 10l3 3 3-3" stroke="#338aff" stroke-width="2" fill="none" stroke-linecap="round"/></svg>
        </div>
      </div>
      <div class="id-card">{{ maskIdCard(currentPatientIdCard) }}</div>
      
      <!-- 就诊信息 -->
      <div class="visit-info">
        <div class="info-row">就诊科室：{{ queueInfo.departmentName }}</div>
        <div class="info-row">医　　生：{{ queueInfo.doctorName }}</div>
        <div class="info-row">我的序号：{{ queueInfo.serialNumber }}</div>
      </div>
      
      <!-- 排队信息：使用计算出的前方人数 -->
      <div class="queue-display">
        <div class="queue-circle">
          <div class="queue-number">{{ aheadCount }}</div>
          <div class="queue-text">前方排队人数</div>
        </div>
      </div>
      
      <!-- 更新按钮 -->
      <div class="update-btn">
        <van-button block type="primary" size="large" @click="fetchQueueInfo">更新</van-button>
      </div>
    </div>
    
    <div v-else class="empty-state">
      <van-loading v-if="loading" size="24px" vertical>加载中...</van-loading>
      <div v-else class="no-data">
        <van-empty description="没有候诊信息" />
      </div>
    </div>

    <!-- 切换就诊人弹窗 -->
    <van-popup
      v-model:show="showPatientPicker"
      position="bottom"
      round
      closeable
      @close="showPatientPicker = false"
      :style="{ maxHeight: '70%' }"
    >
      <div class="patient-picker-container">
        <div class="picker-header">选择就诊人</div>
        <div class="patient-list">
          <!-- 遍历所有患者队列信息 -->
          <div
            v-for="patientQueue in allQueueInfo"
            :key="patientQueue.patientId + '-picker'"
            class="patient-item"
            @click="switchToPatient(patientQueue)"
          >
            <div class="patient-info">
              <span class="patient-name">{{ patientQueue.patientName }}</span>
              <span v-if="patientQueue.patientId === selectedPatientId" class="check-icon">
                <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <circle cx="10" cy="10" r="9" fill="#338aff"/>
                  <path d="M6 10L9 13L14 7" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
              </span>
            </div>
            <div class="patient-meta">
              <span class="serial-number">序号: {{ patientQueue.serialNumber }}</span>
              <!-- 弹窗中显示前方人数 -->
              <span class="ahead-count">前方: {{ patientQueue.patientsAhead }} 人</span>
            </div>
          </div>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { showToast } from 'vant';
import { axiosrmedical } from '@/http/axiosRead';
import { useUserStore } from '@/stores/counter';



// 修正 QueueInfo 接口：根据实际后端返回数据调整
interface QueueInfo {
  patientId: number;
  patientName: string;
  registerId: number;
  departmentName: string;
  doctorName: string;
  serialNumber: number;
  registerStatus: string;
  myQueuePosition: number; // 后端返回的自身位置
  patientsAhead: number;   // 后端返回的前方患者数
  otherPatients: QueuePatient[]; // 其他患者列表
}

// 修正 QueuePatient 接口：根据实际后端返回数据调整
interface QueuePatient {
  patientId: number;
  patientName: string;
  registerId: number;
  serialNumber: number;
  queuePosition: number; // 其他患者的位置
}

interface PatientInfo {
  id: number;
  name: string;
  idCard: string;
  relation: string;
}

const router = useRouter();
const userStore = useUserStore();
const loading = ref(false);
const allQueueInfo = ref<QueueInfo[] | null>(null); 
const selectedPatientId = ref<number | null>(null);
const currentPatientRelation = ref('本人');
const currentPatientIdCard = ref('');
const showPatientPicker = ref(false);
const patientInfoMap = ref<Map<number, PatientInfo>>(new Map());

// 计算当前选中患者的队列信息
const queueInfo = computed(() => {
  if (!allQueueInfo.value || !selectedPatientId.value) return null;
  return allQueueInfo.value.find(item => item.patientId === selectedPatientId.value);
});

// 核心：计算前方排队人数（使用后端返回的patientsAhead字段）
const aheadCount = computed(() => {
  if (!queueInfo.value) return 0;
  // 直接使用后端返回的patientsAhead字段
  return queueInfo.value.patientsAhead;
});

// 掩码身份证号
const maskIdCard = (id: string): string => {
  if (!id) return '';
  return id.replace(/^(.{3}).*(.{4})$/, '$1********$2');
};

// 返回上一页
const onBack = () => {
  router.back();
};

// 切换就诊人
const switchToPatient = async (patientQueue: QueueInfo) => {
  selectedPatientId.value = patientQueue.patientId;
  showPatientPicker.value = false;
  await fetchPatientInfo(patientQueue.patientId);
};

// 获取候诊信息
const fetchQueueInfo = async () => {
  loading.value = true;
  userStore.loadUserInfo();
  
  if (!userStore.accountId) {
    showToast('请先登录');
    router.push('/login');
    loading.value = false;
    return;
  }
  
  try {
    const res = await axiosrmedical.get(`/Patient/GetPatientQueueInfo/queue/${userStore.accountId}`);
    
    if (res.data && res.data.code === 200) {
      allQueueInfo.value = res.data.data; 
      
      // 默认选中第一个患者
      if (allQueueInfo.value && allQueueInfo.value.length > 0) {
        selectedPatientId.value = allQueueInfo.value[0].patientId;
      }
      
      // 预加载所有患者信息
      if (allQueueInfo.value) {
        for (const patientQueue of allQueueInfo.value) {
          await fetchPatientInfo(patientQueue.patientId);
        }
      }
    } else {
      showToast(res.data?.msg || '获取候诊信息失败');
    }
  } catch (error) {
    console.error('获取候诊信息出错:', error);
    showToast('网络错误，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 获取患者详细信息
const fetchPatientInfo = async (patientId: number) => {
  try {
    if (patientInfoMap.value.has(patientId)) {
      const info = patientInfoMap.value.get(patientId);
      if (info && patientId === selectedPatientId.value) {
        currentPatientIdCard.value = info.idCard || '';
        currentPatientRelation.value = info.relation || '本人';
        return;
      }
    }
    
    const res = await axiosrmedical.get('/Patient/GetPatientById', {
      params: { patientId }
    });
    
    if (res.data && res.data.code === 200) {
      const patientInfo = res.data.data;
      if (patientInfo) {
        patientInfoMap.value.set(patientId, patientInfo);
        
        if (patientId === selectedPatientId.value) {
          currentPatientIdCard.value = patientInfo.idCard || '';
          currentPatientRelation.value = patientInfo.relation || '本人';
        }
      }
    }
  } catch (error) {
    console.error('获取患者信息出错:', error);
  }
};

onMounted(() => {
  fetchQueueInfo();
});
</script>

<style scoped>
.queue-query-page {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f8f9fa;
}

/* 患者信息卡片样式 */
.patient-info-card {
  margin: 16px;
  padding: 20px;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

/* 患者头部信息样式 */
.patient-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.patient-name {
  font-size: 20px;
  font-weight: bold;
  color: #333;
}

.relation {
  font-size: 14px;
  color: #666;
  background-color: #f0f2f5;
  padding: 2px 8px;
  border-radius: 10px;
  margin-left: 6px;
  font-weight: normal;
}

.change-patient {
  display: flex;
  align-items: center;
  color: #338aff;
  font-size: 14px;
  cursor: pointer;
}

.id-card {
  color: #999;
  font-size: 14px;
  margin-bottom: 20px;
}

/* 就诊信息样式 */
.visit-info {
  margin-bottom: 24px;
  border-bottom: 1px solid #f0f2f5;
  padding-bottom: 16px;
}

.info-row {
  margin-bottom: 12px;
  color: #333;
  font-size: 15px;
  display: flex;
}

/* 排队信息显示 */
.queue-display {
  display: flex;
  justify-content: center;
  margin: 30px 0;
}

.queue-circle {
  width: 180px;
  height: 180px;
  border-radius: 50%;
  background-color: #f2994a;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: white;
}

.queue-number {
  font-size: 72px;
  font-weight: bold;
  line-height: 1;
  margin-bottom: 8px;
}

.queue-text {
  font-size: 16px;
}

/* 更新按钮样式 */
.update-btn {
  margin-top: 24px;
}

.van-button--primary {
  background-color: #338aff;
  border-color: #338aff;
  border-radius: 8px;
  height: 44px;
  font-size: 16px;
}

/* 空状态样式 */
.empty-state {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
}

.no-data {
  text-align: center;
}

/* 患者选择器样式 */
.patient-picker-container {
  padding: 20px;
}

.picker-header {
  text-align: center;
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f2f5;
}

.patient-list {
  max-height: 400px;
  overflow-y: auto;
}

.patient-item {
  padding: 16px;
  border-bottom: 1px solid #f0f2f5;
  display: flex;
  flex-direction: column;
  cursor: pointer;
}

.patient-item:active {
  background-color: #f8f9fa;
}

.patient-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.patient-meta {
  color: #666;
  font-size: 14px;
  display: flex;
  gap: 12px;
}

.serial-number {
  color: #666;
}

.ahead-count {
  color: #ff6b00;
  background-color: #fff8e6;
  padding: 2px 8px;
  border-radius: 12px;
}

/* 当前选中的患者项 */
.check-icon {
  display: flex;
}
</style>
